import re

from django.contrib.auth.backends import ModelBackend
# from django.contrib.auth.models import User
from apps.users.models import User
from meiduo_mall_chen import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

class UsernameMobileModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        try:
            if re.match(r'1[3-9]\d{9}', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            user = None
        if user is not None and user.check_password(password):
            return user

def generic_verify_url(user_id):

    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)


    token = s.dumps({'userid': user_id})

    return 'http://www.meiduo.site:8000/email_active/?token=%s'%token.decode()
def check_verify_url(token):
    s = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
    try:
        result = s.loads(token)
    except BaseException:
        return None
    userid = result.get('userid')
    return userid

